import React, { FC } from 'react';
import { history } from 'umi';
import {
    setLocalStorageInfo,
} from '@/utils/localStorageInfo';

import type { AppMenu } from '../../../stores/BsinLayoutContext';

import { getUserMenuTreeByAppCode } from '@/services/appMenu';
import { message } from 'antd';
import CompSubmenu from '../submenu';

import './index.less';
import logo2 from '@/assets/logo3.png';
import jiujiu from '@/assets/jiujiu.png';


const MenuItem = (props: { img: string; tips?: string; active?: boolean, onClickGetMenu: Function }) => {
    const { img, tips = '', active = false, onClickGetMenu } = props;

    return <li className={`menu-item ${active ? 'active' : ''}`}>
        <div className='menu-icon' onClick={onClickGetMenu}>
            <img src={img} />
        </div>
        {tips !== '' && <div className='menu-tips'><span>{tips}</span></div>}
    </li>;
};

interface MenuProps {
    apps: any;
}

const Menu: FC<MenuProps> = ({ apps }) => {

    // 子应用信息
    const [appMenu, setAppMenu] = React.useState<AppMenu>();

    // 获取用户子应用菜单
    const getUserApplicationMenu = async (appCode: string) => {
        let res = await getUserMenuTreeByAppCode({ appCode });
        if (res && res.data[0]) {
            setAppMenu(res.data[0]);
        } else {
            message.error(`你没有${appCode}菜单权限`);
            // setTimeout(() => {
            //     history.push('/');
            //     location.reload();
            //     window.localStorage.setItem('bsin-microAppMount', '3');
            // }, 1000);
        }
    };

    /**
       * 点击获取子应用菜单
       * @param app
       */
    const getMenu = async (app: any) => {
        setLocalStorageInfo('bsin-microAppMount', '0');
        // 获取应用菜单
        getUserApplicationMenu(app.appCode)
        // debugger
        history.push('/' + app.appCode);
    };

    console.log(apps)
    return <>
        <div className="menu ">
            <div className='menu-logo'>
                <img src={logo2} />
            </div>
            <ul className="menu-list">
                <MenuItem onClickGetMenu={() => getMenu({ appCode: "bsin-ui-upms" })} tips="jiujiu商城" active={true} img={jiujiu} />
                {apps.appList.map((item) => (
                    <MenuItem onClickGetMenu={() => getMenu(item)} tips={item.appName} active={false} img={item.logo} />
                ))}
            </ul>
        </div>
        <CompSubmenu appMenus={appMenu}/>
    </>
}

export default Menu;